package com.mate.cloud.sentinel;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cong zhi
 * @description
 * @email 448341911@qq.com
 * @date $ $
 * @version: v1.0
 */
@RestController
@RequestMapping("/flow")
public class FlowController {

    @GetMapping("/say-hello")
    @SentinelResource("hot")
    public String sayHello(@RequestParam(value = "name", required = false) String name
            , @RequestParam(value = "age", required = false) Integer age) {
        return "say Hello :" + name + " age:" + age;
    }
    @GetMapping("/hello")
    public String hello() {
        Entry entry = null;
        try {
            entry = SphU.entry("flow");
            System.out.println("web mvc flow limit.");
            return "Hello sentinel";
        } catch (BlockException e) {
            System.out.println("web mvc flow limit!");
            return "web mvc flow limit!";
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
    }

    @GetMapping("/test")
    @SentinelResource(value = "flow", blockHandler = "handlerBlock")
    public String test() {
        System.out.println("test Sentinel");
        return "test Sentinel";
    }

    public String handlerBlock(BlockException e) {
        System.out.println("test Sentinel handlerBlock...." + e);
        return "test Sentinel handlerBlock!";
    }

    /**
     * 初始化bean 之后执行
     */
    @PostConstruct
    public void flowRules() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("flow");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Set limit QPS to 20.
        rule.setCount(2);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }
}
